package com.wqd.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wqd.model.common.dtos.ResponseResult;
import com.wqd.model.common.enums.AppHttpCodeEnum;
import com.wqd.model.user.dtos.LoginDto;
import com.wqd.model.user.pojos.ApUser;
import com.wqd.user.mapper.ApUserMapper;
import com.wqd.user.service.IApUserService;
import com.wqd.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements IApUserService {

    /**
     * 登录接口业务
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        Map map = new HashMap();
        //正常登录（手机号+密码登录）
        if(StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            //先查询是否存在该用户
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone,dto.getPhone()));
            if(apUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"该用户不存在");
            }
            //能走到这里证明有这个用户
            //先获取用户的盐
            String salt = apUser.getSalt();
            //获取用户输入的密码
            String password = dto.getPassword();
            //校验密码,转成md5,再和数据库比对
            password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if(!password.equals(apUser.getPassword())){
                //密码不正确
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码错误");
            }
            //密码正确,生成token
            map.put("token",AppJwtUtil.getToken(apUser.getId().longValue()));
            //为了保证安全性,把slat和pwd置空
            apUser.setPassword("");
            apUser.setSalt("");
            map.put("user",apUser);
            return ResponseResult.okResult(map);
        }else{
            //游客  同样返回token  id = 0
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }


}
